import { 
  Controller, 
  Post, 
  Get, 
  Body, 
  Headers,
  Req,
  Logger,
  BadRequestException
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { Request } from 'express';
import { EnhancedForwardingService } from '../services/enhanced-forwarding.service';
import { ApiProvider, TargetProvider } from '../interfaces/api-adapter.interface';
import { 
  OpenAIChatCompletionRequest,
  OpenAIChatCompletionResponse,
  OpenAIModelsResponse,
  OpenAIEmbeddingRequest,
  OpenAIEmbeddingResponse
} from '../dto/openai.dto';

/**
 * OpenAI API 兼容控制器
 * 提供完整的 OpenAI API 接口，通过适配器转发到 Copilot
 */
@ApiTags('OpenAI API Compatible')
@Controller('openai/v1')
export class OpenAIProxyController {
  private readonly logger = new Logger(OpenAIProxyController.name);

  constructor(private readonly enhancedForwarding: EnhancedForwardingService) {}

  /**
   * OpenAI Chat Completions API
   * 完全兼容 OpenAI 的 chat/completions 接口
   */
  @Post('chat/completions')
  @ApiOperation({ 
    summary: 'Create Chat Completion (OpenAI Compatible)',
    description: 'Creates a model response for the given chat conversation.'
  })
  @ApiResponse({ 
    status: 200, 
    description: 'Chat completion created successfully',
    type: OpenAIChatCompletionResponse
  })
  @ApiResponse({ 
    status: 400, 
    description: 'Invalid request parameters'
  })
  @ApiResponse({ 
    status: 401, 
    description: 'Invalid authentication'
  })
  async createChatCompletion(
    @Body() request: OpenAIChatCompletionRequest,
    @Headers() headers: Record<string, string>,
    @Req() req: Request
  ): Promise<OpenAIChatCompletionResponse> {
    try {
      this.logger.log(`OpenAI chat completion request: model=${request.model}, messages=${request.messages.length}`);
      
      // 验证请求参数
      if (!request.model) {
        throw new BadRequestException('Model is required');
      }
      
      if (!request.messages || request.messages.length === 0) {
        throw new BadRequestException('Messages array cannot be empty');
      }

      const requestInfo = {
        headers,
        ip: req.ip,
        userAgent: req.get('User-Agent'),
        endpoint: 'chat/completions'
      };

      // 使用增强转发服务，通过 OpenAI 适配器转发到 Copilot
      const result = await this.enhancedForwarding.forwardApiRequest(
        ApiProvider.OPENAI,
        TargetProvider.COPILOT,
        request,
        requestInfo
      );

      return result;
    } catch (error) {
      this.logger.error(`OpenAI chat completion failed: ${error.message}`);
      throw error;
    }
  }

  /**
   * OpenAI Models API
   * 列出可用的模型
   */
  @Get('models')
  @ApiOperation({ 
    summary: 'List Models (OpenAI Compatible)',
    description: 'Lists the currently available models, and provides basic information about each one.'
  })
  @ApiResponse({ 
    status: 200, 
    description: 'Models listed successfully',
    type: OpenAIModelsResponse
  })
  async listModels(@Headers() headers: Record<string, string>): Promise<OpenAIModelsResponse> {
    this.logger.log('OpenAI models list request');
    
    return {
      object: "list",
      data: [
        {
          id: "gpt-4o",
          object: "model",
          created: 1686935002,
          owned_by: "openai"
        },
        {
          id: "gpt-4o-mini", 
          object: "model",
          created: 1686935002,
          owned_by: "openai"
        },
        {
          id: "gpt-3.5-turbo",
          object: "model", 
          created: 1686935002,
          owned_by: "openai"
        },
        {
          id: "gpt-4-turbo",
          object: "model",
          created: 1686935002,
          owned_by: "openai"
        },
        {
          id: "gpt-4",
          object: "model",
          created: 1686935002,
          owned_by: "openai"
        }
      ]
    };
  }

  /**
   * OpenAI Embeddings API
   */
  @Post('embeddings')
  @ApiOperation({ 
    summary: 'Create Embeddings (OpenAI Compatible)',
    description: 'Get a vector representation of a given input that can be easily consumed by machine learning models and algorithms.'
  })
  @ApiResponse({ 
    status: 200, 
    description: 'Embeddings created successfully',
    type: OpenAIEmbeddingResponse
  })
  @ApiResponse({ 
    status: 400, 
    description: 'Invalid request parameters'
  })
  async createEmbeddings(
    @Body() request: OpenAIEmbeddingRequest,
    @Headers() headers: Record<string, string>,
    @Req() req: Request
  ): Promise<OpenAIEmbeddingResponse> {
    try {
      this.logger.log(`OpenAI embeddings request: model=${request.model}`);
      
      // 验证请求参数
      if (!request.model) {
        throw new BadRequestException('Model is required');
      }
      
      if (!request.input) {
        throw new BadRequestException('Input is required');
      }

      const requestInfo = {
        headers,
        ip: req.ip,
        userAgent: req.get('User-Agent'),
        endpoint: 'embeddings'
      };

      // 使用增强转发服务，通过 OpenAI 适配器转发到 Copilot
      const result = await this.enhancedForwarding.forwardApiRequest(
        ApiProvider.OPENAI,
        TargetProvider.COPILOT,
        request,
        requestInfo
      );

      return result;
    } catch (error) {
      this.logger.error(`OpenAI embeddings failed: ${error.message}`);
      // 如果目标API不支持embeddings，返回适当的错误
      if (error.message.includes('not supported')) {
        throw new BadRequestException('Embeddings not supported by target API');
      }
      throw error;
    }
  }

  /**
   * OpenAI Completions API (Legacy)
   */
  @Post('completions')
  @ApiOperation({ 
    summary: 'Create Completion (OpenAI Compatible - Legacy)',
    description: 'Creates a completion for the provided prompt and parameters. This is the older completions API.'
  })
  @ApiResponse({ 
    status: 200, 
    description: 'Completion created successfully'
  })
  async createCompletion(
    @Body() request: any,
    @Headers() headers: Record<string, string>,
    @Req() req: Request
  ) {
    try {
      this.logger.log(`OpenAI completion request: model=${request.model}`);
      
      if (!request.model) {
        throw new BadRequestException('Model is required');
      }
      
      if (!request.prompt) {
        throw new BadRequestException('Prompt is required');
      }

      const requestInfo = {
        headers,
        ip: req.ip,
        userAgent: req.get('User-Agent'),
        endpoint: 'completions'
      };

      // 使用增强转发服务转发到目标API
      const result = await this.enhancedForwarding.forwardApiRequest(
        ApiProvider.OPENAI,
        TargetProvider.COPILOT,
        request,
        requestInfo
      );

      return result;
    } catch (error) {
      this.logger.error(`OpenAI completion failed: ${error.message}`);
      throw error;
    }
  }

  /**
   * 获取OpenAI API健康状态
   */
  @Get('health')
  @ApiOperation({ 
    summary: 'OpenAI API Health Check',
    description: 'Check the health status of OpenAI API forwarding'
  })
  async getHealth() {
    this.logger.log('OpenAI health check request');
    
    return {
      status: 'healthy',
      timestamp: new Date().toISOString(),
      provider: 'OpenAI',
      target: 'Copilot',
      available_endpoints: [
        'POST /openai/v1/chat/completions',
        'POST /openai/v1/completions',
        'POST /openai/v1/embeddings',
        'GET /openai/v1/models',
        'GET /openai/v1/health'
      ]
    };
  }
}